<?php


namespace app\admin\model\base;
use app\BaseModel;

/**
 * 学生模型
 * Class Student
 * @package app\admin\model\base
 */
class Student extends BaseModel
{
    /**
     * 关联专业
     * @return \think\model\relation\HasOne
     */
    public function special(){
        return $this->hasOne(Special::class,'id','special_id')->field('name,id');
    }
    /**
     * 关联年级
     * @return \think\model\relation\HasOne
     */
    public function grades(){
        return $this->hasOne(Grades::class,'id','grades_id')->field('name,id');
    }

    /**
     * 关联班级
     * @return \think\model\relation\HasOne
     */
    public function classes(){
        return $this->hasOne(Classes::class,'id','classes_id')->field('name,id');
    }


    /**
     * 获取用户列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @param string $orderby
     * @param string $field
     * @return array
     */
    public static function getList(array $where, int $page, int $limit, string $orderby = '', string $field = '*'): array
    {
        //查询
        $data = self::field($field)
            ->with(['special','grades','classes'])
            ->where($where)
            ->order($orderby)
            ->paginate(['list_rows' => $limit, 'page' => $page], false)
            ->toArray();
        //遍历数组
        $lists = [];
        $attr = StudentGroup::select()->toArray();
        if(!empty($attr)){
            $lists = array_column($attr,'name','id');
        }
        foreach ($data['data'] as $k=>&$v) {
            $attrs = !empty($v['student_group_id']) ? explode(',',$v['student_group_id']) : [];
            $str = [];
            if(!empty($attrs) && !empty($lists)){
                foreach ($attrs as $vv){
                    if(isset($lists[$vv])) $str[] = $lists[$vv];
                }
            }
            $data['data'][$k]['student_group_name'] = $str;
            unset($v['password']);
            unset($v['safe_code']);
        }
        return $data;
    }

}